#!/usr/bin/env ruby

# require mysql ruby-module
require "mysql"

#
# Database handler
#
class DatabaseHandler
  def initialize()
    @address = "localhost"
    @username = "root"
    @password = "aurtjet4"
    @dbname = "test"
    @dbh = nil
  end
  
  # initiate database connection
  def connect
    @dbh = Mysql.new(@address, @username, @password, @dbname)
  end
  
  # close database connection
  def close
    @dbh.close if @dbh
  end
  
  # query db
  def query(q)
    # number of retries
    c = 4;
    
    count = 0
    
    begin
      r = @dbh.query(q)
      
    rescue
      r = @dbh.query(q)
      
    end
    
    return r
  end
    
  # get directory path from DB
  # @returns path as string
  def get_path
    result = self.query("SELECT dir from settings where id = 1 LIMIT 0, 30 ")
    r = result.fetch_row
    r = r[0]
    
    return r
  end
  
  # reset directory table
  def path_processed
    result = @dbh.query("UPDATE settings SET dir = \"\" WHERE id = 1")
  end
  
  # escape string
  def escape_string(string)
    return @dbh.escape_string(string)
  end
  
  # insert image information into database
  def add_image(exif_info)
    begin
      # With GPS info
      if (exif_info.length > 3) 
        q = ("INSERT INTO image (filename, date_time,
                            category, gps_latitude, 
                            gps_longitude) VALUES (
                            '#{exif_info[0]}',
                            '#{exif_info[1]}',
                            '#{exif_info[2]}',
                            '#{exif_info[3]}',
                            '#{exif_info[5]}')")       
        result = @dbh.query(q)
        #debug("--exif info > 3")
        
      # without GPS info
      else
        q = ("INSERT INTO image (filename, date_time,
                        category ) VALUES (
                        '#{exif_info[0]}',
                        '#{exif_info[1]}',
                        '#{exif_info[2]}')")
        result = @dbh.query(q)
        #debug("--exif info = 3")
      end
      
    rescue
      puts @dbh.error()  
    
    end
    
    return result
  end
  
end